# -*- coding: utf-8 -*-
#coding=utf-8

import os
import os.path as _path
import tkinter as tk
import tkinter.messagebox as messagebox
from tkinter.filedialog import askdirectory
from tkinter.filedialog import askopenfilename
from os import path
import requests
import threading
import random
import time

root = tk.Tk() # TK对象
csvFile = tk.StringVar()
outputPathSelector = tk.StringVar()
counter = 1
msg = tk.StringVar()
msg2 = tk.StringVar()
msg3 = tk.StringVar()
errorMsg = tk.StringVar()

def main():

    draw_window(root,"导图片")

    root.mainloop()   # 这里进入顶层窗口的循环



# 窗口样子的设置
def draw_window(root,title):

    root.title(title)  # 设置主窗口的标题

    # 标签控件，显示文本和位图，展示在第一行
    tk.Label(root, text="*csv文件").grid(row=0,sticky='E')
    tk.Label(root, text="导出路径").grid(row=1,sticky='W')  # 第二行

    tk.Entry(root,textvariable = csvFile,state='readonly',width=35).grid(row=0, column=1)
    tk.Button(root, text="..", command=selectFile).grid(row=0, column=2)

    tk.Entry(root, textvariable=outputPathSelector, state='readonly',width=35).grid(row=1, column=1)
    tk.Button(root, text="..", command=selectPath).grid(row=1, column=2)

    tk.Button(root,text='开始导出',command=lambda: exportPic()).grid(row=2,column=1)

    tk.Label(root, textvariable=msg).grid(row=3,rowspan=3,columnspan=4)
    tk.Label(root, textvariable=msg2).grid(row=7,rowspan=3,columnspan=4)
    tk.Label(root, textvariable=msg3).grid(row=11,rowspan=2,columnspan=4)
    tk.Label(root, textvariable=errorMsg).grid(row=14,rowspan=3,columnspan=4)

    root.update_idletasks()
    sw = root.winfo_screenwidth()  # 得到屏幕宽度
    sh = root.winfo_screenheight()  # 得到屏幕高度
    nCurWid = root.winfo_reqwidth()
    nCurHeight = root.winfo_reqheight()
    root.geometry("%dx%d+%d+%d" % (nCurWid, nCurHeight, sw / 2 - nCurWid / 2, sh / 2 - nCurHeight / 2))
    root.resizable(False, False)  # 禁止缩放


def exportPic():

    clearMsg()

    # 检查路径是否都选择了
    if csvFile.get().strip()=="":
        messagebox.showerror("ERROR!!!","请选择csv文件，亲")
        return

    outputPath = ""

    if outputPathSelector.get().strip()=="":
        outputPath = os.path.dirname(csvFile.get().strip()) + os.sep + "导图片-" + str(int(time.time()))
        mk_dir(outputPath)
    else:
        outputPath = outputPathSelector.get().strip()
    

    global counter
    counter = int(counter) + 1

    with open(outputPath + os.sep + "已导出.csv", "w") as wfd:
            # with open("./data/car_data.csv", 'r', encoding='utf-8') as fd:
        with open(csvFile.get(), 'r', encoding='utf-8') as fd:
            lines = fd.readlines()
            lineNum = 0
            line1 = []
            line1Size = 0
            for line in lines:
                try:
                    if len(line.strip('\n').split(";"))<2:
                        vin, rest = line.strip('\n').split(",", maxsplit=1)
                        list = rest.split(",", maxsplit=16)
                    else:
                        vin, rest = line.strip('\n').split(";", maxsplit=1)
                        list = rest.split(";", maxsplit=16)
                    vin = vin.strip('"')
                    if lineNum == 0:
                        line1 = list
                        line1Size = len(list)
                    msg.set("正在导出第 " + str(lineNum) + " 个")
                    msg2.set("vin码为 " + vin)
                    vin_dir_path = path.join(outputPath, vin)
                    listSize = len(list)
                    for index in range(listSize):
                        if(line1Size < listSize):
                            name = "img-"+str(index)
                        else:
                            name = line1[index].strip('"')
                        if name != "":
                            msg3.set("下载字段:" + name)
                            root.update()  # 更新界面
                            # messagebox.showinfo("出错", list[index])
                            threading.Thread(target=download(name, list[index], base_dir=vin_dir_path),name='downloadThread-' + name + str(random.randint(0, 1000))).start()

                    wfd.write(vin + "\n")
                    lineNum = lineNum + 1
                except Exception as e:
                    messagebox.showinfo("出错", str(e))
                    return
    clearMsg()
    messagebox.showinfo("提示","导出完毕...")

def clearMsg():
    msg.set("")
    msg2.set("")
    errorMsg.set("")

def selectFile():
    filename = askopenfilename(filetypes = [('CSV', 'csv')])
    if filename != '':
        csvFile.set(filename)

def selectPath():
    path_ = askdirectory()
    # print(path_)
    outputPathSelector.set(path_)


def download(filename: str, images: str, base_dir: str):
    # messagebox.showinfo("下载图片", images)
    image_urls = images.split(',')
    idx = 0
    for url in image_urls:
        url = url.strip('"')
        if not url.startswith("http"):
            return
        if len(image_urls) > 1:
            image_file_name = '%s-%d%s' % (filename, idx, url[url.rindex('.'):])
            idx += 1
        else:
            image_file_name = '%s%s' % (filename, url[url.rindex('.'):])
        image_file_path = path.join(base_dir, image_file_name)
        print("导出:", image_file_path)
        mk_dir(base_dir)

        while True:
            try:
                with open(image_file_path, 'wb') as fd:
                    resp = requests.get(url)
                    fd.write(resp.content)
                break
            except Exception:
                print("重试: %s" % url)


def nameMapper(nameInDB):
    nameInDB = nameInDB.strip('"')
    switcher = {
        "vehicle_license_imgs": "xingshizheng",
        "registration_imgs": "dengjizheng",
        "purchase_invoice_img": "gouchefapiao",
        "nameplate_imgs": "mingpai",
        "manufacturer_certificate_imgs": "hegezheng",
        "jiaoqiangxian": "jiaoqiangxian",
        "shangyexian": "shangyexian",
        "gouzhishui": "gouzhishui",
        "driving_license_imgs":"jiashizheng",
        "insurance_img":"baoxiandan"
    }
    return switcher.get(nameInDB, "nothing")


lock = threading.RLock()
def mk_dir(path: str, recursive=True):
    """
    创建目录, 支持递归创建, 线程安全
    :param path: 路径名
    :param recursive: 是否支持递归创建, True支持, False不支持, 默认支持
    """
    if not path or path == '':
        raise IOError("路径错误: {}".format(path))
    if _path.exists(path):
        pass
    else:
        parent_path = _path.dirname(path)
        if not (recursive or _path.exists(parent_path)):
            raise IOError("父路径: {} 不存在".format(parent_path))
        mk_dir(parent_path)
        with lock:
            if not _path.exists(path):
                os.mkdir(path)

if __name__ == '__main__':
    main()